package com.w1.security.service.impl.security;

import com.alibaba.fastjson.JSON;
import com.w1.security.domain.LoginUser;
import com.w1.security.domain.User;
import com.w1.security.utiles.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * jwt解密类
 * @author mingyifan
 * @date 2022-03-05 14:01
 */
@Component
public class JwtDecryptService {
    public LoginUser parseJwt(HttpServletRequest request){
        //先拿head
        String Authorization = request.getHeader("Authorization");
        //如果没有值就再从cookie里试下，有就算了
        if (!StringUtils.hasText(Authorization)){
            //head没有，从cookie里试试
            Cookie[] cookies = request.getCookies();
            //npe判断
            if (!ObjectUtils.isEmpty(cookies)){
                for (Cookie cookie : cookies) {
                    if ("Authorization".equals(cookie.getName())){
                        Authorization=cookie.getValue();
                    }
                }
            }

        }
        if (StringUtils.hasText(Authorization)) {
            Claims claims = JwtUtil.parseJWT(Authorization);
            User user = JSON.parseObject(claims.getSubject(), User.class);
            return new LoginUser(user,new ArrayList<>());
        }
        return null;
    }
}
